/*
 * Copyright (C) 2015 备胎金服
 * 未经授权允许不得进行拷贝和修改
 *   http://www.btjf.com/
 */
package com.zhangman.framework.implementation;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import com.zhangman.framework.Audio;
import com.zhangman.framework.Music;
import com.zhangman.framework.Sound;
import java.io.IOException;

/**
 * Created by zhangman on 2016/11/1 11:33.
 * Email: zhangman523@126.com
 */
public class AndroidAudio implements Audio {
  AssetManager mAssetManager;
  SoundPool mSoundPool;

  public AndroidAudio(Activity activity) {
    activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    this.mAssetManager = activity.getAssets();
    this.mSoundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
  }

  @Override public Music createMusic(String file) {
    try {
      AssetFileDescriptor assetFileDescriptor = mAssetManager.openFd(file);
      return new AndroidMusic(assetFileDescriptor);
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException("Couldn't load music '" + file + "'");
    }
  }

  @Override public Sound createSound(String file) {
    try {
      AssetFileDescriptor assetFileDescriptor = mAssetManager.openFd(file);
      int soundId = mSoundPool.load(assetFileDescriptor, 0);
      return new AndroidSound(mSoundPool, soundId);
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException("Couldn't load sound '" + file + "'");
    }
  }
}
